<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('1000px')"
    :visible="visible"
    :title="title"
    @open="open"
    @close="close"
  >
    <template v-if="step === 1">
      <el-form
        ref="firstForm"
        :model="nodeData"
        label-width="auto"
        :rules="rules"
        class="flex flex-wrap pr-30"
      >
        <el-form-item :label="$t('BELONGS_REGION_STATION_NAME')" prop="stationId" class="w-100">
          <el-input v-model="nodeData.stationId" class="hide" />
          <!-- 区域选择 -->
          <region-cascader
            class="block"
            :selected-ids="[nodeData.stationId]"
            :clearable="false"
            data-name="stationTree"
            placeholder="REGION_STATION"
            :disabled="
              type === 'mod' &&
                ((oldStationId === nodeData.stationId &&
                  (stationData.status === 'CONSIGN' || stationData.status === 'REPAIR')) ||
                  segmentList.length > 0)
            "
            @change="regionChange"
          />
        </el-form-item>
        <!-- <el-form-item :label="$t('STATION_CODE')" class="w-50">
          <el-input :value="nodeData.stationId" readonly />
        </el-form-item> -->
        <el-form-item :label="$t('BELONGS_ROOM_NAME')" class="w-50">
          <el-select
            v-model="nodeData.roomId"
            :disabled="type === 'mod' && segmentList.length > 0 && nodeData.roomId !== ''"
            clearable
            placeholder=""
          >
            <el-option
              v-for="item in roomList"
              :key="item.regionId"
              :value="item.regionId"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('NODE_TYPE')" prop="nodeType" class="w-50">
          <el-select
            v-model="nodeData.nodeType"
            placeholder=""
            :disabled="type !== 'add'"
          >
            <el-option
              v-for="item in nodeTypes"
              :key="item.id"
              :value="item.code"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('NODE_NAME')" prop="nodeName" class="w-50">
          <el-select
            v-if="nodeData.nodeCategory === 'AFS' && type === 'add'"
            v-model="afsId"
            placeholder=""
            filterable
            @change="nodeNameChanged"
          >
            <el-option
              v-for="item in deviceList"
              :key="item.deviceId"
              :value="item.deviceId"
              :label="item.deviceName"
            />
          </el-select>
          <template v-else>
            <!-- <el-tooltip :content="$t('CHARACTERS_SUGGEST', {msg: '~%&[]{}()=_+'})" placement="top" effect="light"> -->
            <el-input v-model.trim="nodeData.nodeName" maxlength="50" />
            <!-- </el-tooltip> -->
          </template>
        </el-form-item>
        <el-form-item :label="$t('NODE_MODEL')" class="w-50">
          <el-input
            v-model="nodeData.model"
            maxlength="32"
            :readonly="nodeData.nodeType === 'AFS' || nodeData.nodeType === 'AOCC'"
          />
        </el-form-item>
        <el-form-item :label="$t('RESOURCE_CODE')" class="w-50">
          <el-input v-model="nodeData.resourceCode" maxlength="32" />
        </el-form-item>
        <el-form-item :label="$t('VENDOR')" class="w-50">
          <el-input v-model="nodeData.company" maxlength="32" />
        </el-form-item>
      </el-form>
    </template>
    <template v-else>
      <light-split
        v-if="nodeData.nodeCategory === 'LIGHT_SPLIT'"
        ref="LIGHT_SPLIT"
        :device-prop="nodeData.properties"
      />
      <flange
        v-if="nodeData.nodeCategory === 'ODF'"
        ref="ODF"
        :device-prop="nodeData.properties"
        :type="type"
      />
      <Transmission
        v-if="nodeData.nodeCategory === 'TRANSPORT'"
        ref="TRANSPORT"
        :device-prop="nodeData.properties"
        :row-data="rowData"
        :type="type"
      />
    </template>
    <template v-slot:footer>
      <el-button @click="close">{{ $t('CANCEL') }}</el-button>
      <template v-if="nodeData.nodeCategory !== 'AFS'">
        <el-button v-if="step == 1" @click="next">{{ $t('NEXT') }}</el-button>
        <el-button v-else @click="step = 1">{{ $t('PREVIOUS') }}</el-button>
      </template>
      <el-button
        v-if="step == 2 || nodeData.nodeCategory === 'AFS'"
        type="primary"
        @click="$debounce(save)"
      >{{ $t('SAVE') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import nodeApi from '@/api/oen/NodeApi'
  import NetworkSegmentApi from '@/api/oen/NetworkSegmentApi'
  import RegionCascader from '@/components/RegionCascader'
  import LightSplit from './components/second/LightSplit'
  import Flange from './components/second/Flange'
  import Transmission from './components/second/Transmission'

  export default {
    components: { RegionCascader, LightSplit, Flange, Transmission },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: ''
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        step: 1,
        roomList: [],
        nodeData: {
          nodeCategory: '',
          nodeType: '',
          nodeName: '',
          nodeId: '',
          stationId: '',
          roomId: '',
          resourceCode: '',
          company: '',
          model: '',
          properties: {
            odf: {
              faceNum: 1,
              flangeType: 'LC',
              faceList: [
                {
                  capacity: 12,
                  connNum: 0,
                  faceName: 'P1',
                  idleNum: 0,
                  installNum: 12
                }
              ]
            },
            //
            split: {
              inNum: 1,
              outNum: ''
            },
            trans: {
              shelfNum: 1,
              shelfList: []
            }
          }
        },
        stationData: {},
        oldStationId: '',
        deviceList: [],
        afsId: '',
        segmentList: []
      }
    },
    computed: {
      ...mapGetters(['baseRegionList', 'allNodeTypes']),
      nodeTypes() {
        if (this.type === 'add') {
          return this.allNodeTypes.filter(i => i.code !== 'SPLICE_CLOSURE' && i.code !== 'AFS' && i.code !== 'CLUSTER' && i.code !== 'AOCC')
        }
        return this.allNodeTypes.filter(i => i.code !== 'SPLICE_CLOSURE')
      },
      title() {
        const titleName = {
          view: this.$t('VIEW_NODE'),
          add: this.$t('ADDE_NODE'),
          mod: this.$t('EDIT_NODE')
        }
        return titleName[this.type]
      },
      rules() {
        return {
          stationId: [
            {
              required: true,
              message: this.$t('SELECT_STATION'),
              trigger: 'change'
            }
          ],
          nodeType: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('NODE_TYPE'),
              trigger: 'change'
            }
          ],
          nodeName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('NODE_NAME'),
              trigger: 'blur'
            }
          ]
        }
      }
    },
    watch: {
      'nodeData.nodeType': function(val) {
        const nodeTypeData = this.allNodeTypes.find(i => i.code === val)
        this.nodeData.nodeCategory = nodeTypeData ? nodeTypeData.nodeCategory : ''
        if (this.type === 'add') {
          this.nodeData.nodeId = ''
        }
        if (this.nodeData.nodeCategory === 'AFS' && this.type === 'add') {
          this.nodeData.model = ''
          this.getNotExistsNodeList()
        }
      }
    },
    methods: {
      getLinkNode() {
        this.segmentList = []
        NetworkSegmentApi.linkNode({
          nodeId: this.rowData.nodeId
        }).then(res => {
          this.segmentList = res || []
        })
      },
      nodeNameChanged() {
        const afsNode = this.deviceList.find(i => i.deviceId === this.afsId)
        this.nodeData.nodeId = this.afsId
        this.nodeData.nodeName = afsNode.deviceName
        this.nodeData.model = afsNode.model
        this.nodeData.company = afsNode.company
        console.log('this.nodeData', this.nodeData)
      },
      // 从AFS获取某节点类型不存在的节点
      getNotExistsNodeList() {
        this.nodeData.nodeName = ''
        this.afsId = ''
        this.deviceList = []
        nodeApi
          .getNotExistsNodeList({
            afsType: this.nodeData.nodeType
          })
          .then(res => {
            this.deviceList = res || []
          })
      },
      open() {
        this.step = 1
        this.$nextTick(() => {
          this.$refs.firstForm && this.$refs.firstForm.clearValidate()
          this.nodeData.roomId = this.rowData.roomId || ''
        })
        const newData = this.$options.data().nodeData
        this.nodeData = this.rowData.id ? { ...newData, ...this.rowData } : newData
        // 修改情况下，节点所属站点已删除，置空站点id
        if (
          this.type !== 'add' &&
          !this.baseRegionList.some(i => i.regionId === this.nodeData.stationId)
        ) {
          this.nodeData.stationId = ''
        }
        this.oldStationId = this.nodeData.stationId
        this.segmentList = []
        // if (this.type === 'mod' && this.oldStationId !== '') {
        //   this.getLinkNode()
        // }
      },
      // 下一步
      next() {
        this.$refs.firstForm.validate(valid => {
          if (valid) {
            this.step = 2
          }
        })
      },
      // 保存
      save() {
        if (document.getElementsByClassName('el-message--error').length) return
        if (this.nodeData.nodeCategory === 'LIGHT_SPLIT') {
          delete this.nodeData.properties.odf
          delete this.nodeData.properties.trans
        }
        if (this.nodeData.nodeCategory === 'ODF') {
          delete this.nodeData.properties.split
          delete this.nodeData.properties.trans
          const faceList = this.nodeData.properties.odf.faceList
          if (faceList.some(i => i.faceName === '')) {
            this.$message.error(this.$t('ENTER_FACE_NAME'))
            return
          }
        }
        if (this.nodeData.nodeCategory === 'TRANSPORT') {
          const shelfList = this.nodeData.properties.trans.shelfList
          if (shelfList.some(i => i.slotList.some(j => j.slotName === ''))) {
            this.$message.error(this.$t('ENTER_SLOT_NAME'))
            return
          }
          delete this.nodeData.properties.odf
          delete this.nodeData.properties.split
        }
        // afs设备校验
        if (this.nodeData.nodeCategory === 'AFS') {
          this.$refs.firstForm.validate(valid => {
            if (!valid) return
            this.nodeData.id ? this.updateNode() : this.addNode()
          })
        } else {
          // 第二步校验
          this.$refs[this.nodeData.nodeCategory].$refs.form.validate(valid => {
            if (!valid) return
            this.nodeData.id ? this.updateNode() : this.addNode()
          })
        }
      },
      // 新增节点
      addNode() {
        nodeApi.add(this.nodeData).then(res => {
          this.$message.success(this.$t('ADD_SUCCESS'))
          this.close(true)
        })
      },
      // 更新节点信息
      updateNode() {
        nodeApi.mod(this.nodeData).then(res => {
          this.$message.success(this.$t('MODIFY_SUCCESS'))
          this.close(true)
        })
      },
      // 区域搜索条件改变
      regionChange(data) {
        console.log('regionChange-----', data)
        this.nodeData.roomId = ''
        this.roomList = this.baseRegionList.filter(i => i.parentId === data)
        this.nodeData.stationId = data
        this.stationData = this.baseRegionList.find(i => i.regionId === data) || {}
      },
      close(load) {
        this.$emit('close', load)
        this.nodeData = this.$options.data().nodeData
        this.$nextTick(() => {
          this.$refs.firstForm && this.$refs.firstForm.clearValidate()
        })
      }
    }
  }
</script>

<style scoped></style>
